import axios from 'axios'
import { showToast } from "vant" // 引入提示组件

// window.apibasrurl = 'http://47.104.200.167:8076'
window.apibasrurl = 'https://mockapi.eolink.com/I5GcBE7f2ec2e412269ba0036612578a9b3e1bc30976db6'

if (location.host == '120.27.83.2:9123') {
    apibasrurl = 'http://120.27.83.2:9123'
}

const generateApiMap = (map) => {
    let facade = {}
    for (let el in map) {
        facade[el] = toMethod(map[el]);
    }
    return facade
};
const toMethod = (options) => {
    options.method = options.method || 'post'
    return (params = {}, attachedParams, config = {}) => {
        // 允许会话失效，不处理会话失效的逻辑
        config.allowSessionFail = options.allowSessionFail
        // 转换变量
        config.varConversion = options.varConversion

        // if (options.isId) {
        //     // options.url = options.url + query.id
        // }

        return sendApiInstance(options.method, options.url, params, config, options.isType, options.Type, options.baseURL)
    }
}
// 创建axios实例
const createApiInstance = (config = {}, Type, isType = {}, params = {}) => {
    const _config = {
        withCredentials: true, // 跨域
        baseURL: apibasrurl,
        headers: {
            'Authorization': 'Bearer' + sessionStorage.getItem('token'),
            'Content-Type': Type && Type != 'download' ? Type : 'application/json'
        },
        params: {}
    }

    if (isType.cancelToken) {
        _config.cancelToken = new axios.CancelToken(function executor(c) {
            window.source = c;
        })
    }

    config = Object.assign(_config, config);

    return axios.create(config)
}
function backFormData(d) {
    let f = new FormData();
    for (let el in d) {
        f.append(el, d[el])
    }
    return f
}
const sendApiInstance = (method, url, params, config = {}, isType = {}, Type, baseUrl) => {
    if (config.varConversion) {
        params = decamelize(params)
    }
    if (method === 'get') {
        // params: Object.assign({}, params)
        // url = url + params.id
    }
    if (method === 'post') {
        let userInfoJson = sessionStorage.getItem('userInfo') || {}
        if (userInfoJson) {
            try {
                let userInfo = JSON.parse(userInfoJson) || {}

                window.userInfo = userInfo
                params.access_token = userInfo.access_token;
            } catch (e) {
                console.log(e)
            }
        }
        if (!Type) {
            params = backFormData(params);
        }
    }
    if (!url) { return }
    let instance = createApiInstance(config, Type, isType, params)

    instance.interceptors.response.use(response => {
        if (Type && Type == 'download') {
            const filename = response.headers['content-disposition'] && response.headers['content-disposition'].split('=')[1] || '文件下载.xlsx'
            downloadFile(response.data, filename)
            Promise.resolve();
            return
        }

        let { code, data, msg } = response.data

        if (config.varConversion) {
            data = camelcase(data)
        }

        if (code == 0 || 20000) {
            if (isType.reload) {
                location.reload()
            }
            if (!data) {
                return msg
            }
            return data
        } else {
            // if(code=='104') {
            // 	window.location.href = '/login'
            // 	return
            // }
            showToast(msg)
            // throw new Error(data)
        }
    }, error => {
        // if (window.isStop) {
        //     window.isStop = ''
        //     return
        // }

        return Promise.reject(error).catch(() => { })
    })
    return instance[method](url, params, config)
}

// 文件流形式文件下载
const downloadFile = (data, filename) => {
    // 接收的是blob，若接收的是文件流，需要转化一下
    var blob = new Blob([data], { type: 'application/vnd.ms-excel' })
    if (typeof window.chrome !== 'undefined') {
        // Chrome version
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(data);
        link.download = filename;
        link.click();
    } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // IE version
        blob = new Blob([data], { type: 'application/force-download' });
        window.navigator.msSaveBlob(blob, filename);
    } else {
        // Firefox version
        var file = new File([data], filename, { type: 'application/force-download' });
        window.open(URL.createObjectURL(file));
    }
}
export default {
    generateApiMap
}
